package com.example.myimageshare.View;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.myimageshare.R;
import com.example.myimageshare.domain.User;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

public class LoginActivity extends AppCompatActivity {

    //组件
    private EditText et_username;
    private EditText et_password;

    private Button btn_login;
    private Button btn_register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        initListener();

    }

    /*组件绑定*/
    private void initView(){
        et_username = findViewById(R.id.UserNameEdit);
        et_password = findViewById(R.id.PassWordEdit);

        btn_login = findViewById(R.id.LoginButton);
        btn_register = findViewById(R.id.RegisterButton);
    }



    /*事件绑定*/
    private void initListener(){

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
                setResult(1);
                finish();
            }
        });

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
            }
        });
    }

    /*登录
    * 同时，BmobUser在本地缓存了登录的用户数据*/
    private void login() {
        final User user = new User();
        user.setUsername(et_username.getText().toString());
        user.setPassword(et_password.getText().toString());
        user.login(new SaveListener<User>() {
            @Override
            public void done(User bmobUser, BmobException e) {
                if (e == null) {
                    Log.d("MainActicity","登录成功");
                    Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                    this.onFinish();
                } else {
                    Log.d("MainActicity","登录失败");
                    Toast.makeText(LoginActivity.this,"登录失败请检查输入",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}
